<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            round
            @click="openDrawer('add')"
          >
            添加面经
          </el-button>
        </div>
      </template>
      <!-- :data:  数据源（要渲染的数组） -->
      <!-- label: 表头（列表） -->
      <!-- width: 列宽 -->
      <!-- prop： 要渲染的字段名 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="stem" label="标题" width="180">
        </el-table-column>
        <el-table-column prop="creator" label="作者" width="180">
        </el-table-column>
        <el-table-column prop="likeCount" label="点赞"></el-table-column>
        <el-table-column prop="views" label="浏览数"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <div class="actions">
              <i
                class="el-icon-view"
                @click="openDrawer('preview', row.id)"
              ></i>
              <i
                class="el-icon-edit-outline"
                @click="openDrawer('edit', row.id)"
              ></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- current-page: 配置的当前页 -->
      <!-- page-sizes：配置每页的页容量 -->
      <!-- page-size： 当前页的页容量 page-size的值和page-sizes配置的数组中的第一个值保持一致-->
      <!-- layout：分页器的样式展示 -->
      <!-- total: 表示一共有多少条数据 -->
      <!-- @size-change：切换页容量时触发 -->
      <!-- @current-change： 切换页码时触发 -->
      <!-- <el-pagination
        :current-page="current"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination> -->
      <el-pagination
        background
        :current-page="current"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </el-card>
    <!-- visible:控制抽屉的显示隐藏 -->
    <!-- direction：抽屉打开的方向 rtl / ltr / ttb / btt -->
    <!-- before-close：关闭之前的一个回调函数 -->
    <!-- size: 抽屉的大小 -->
    <!-- title：配置抽屉的标题 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      size="60%"
      @close="handleClose"
    >
      <div v-if="drawerType === 'preview'" class="article-preview">
        <h5>{{form.stem}}</h5>
        <!-- <div>{{form.content}}</div> -->
        <div v-html="form.content"></div>
      </div>
      <!-- el-form :model  :rules -->
      <!-- el-form-item prop -->
      <!-- el-input v-model -->
      <el-form v-else ref="form" label-width="80px" :model="form" :rules="rules">
        <el-form-item label="标题" prop="stem">
          <el-input placeholder="输入面经标题" v-model="form.stem"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quillEditor
            v-model="form.content"
            @blur="$refs.form.validateField('content')"
          ></quillEditor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirmAdd">确认</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  getArticleListApi,
  createArticleApi,
  delArticleApi,
  getArticleDetailApi,
  editArticleApi
} from '@/api/article'
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
export default {
  name: 'article-page',
  components: {
    quillEditor
  },
  data () {
    return {
      // 当前页码
      current: 1,
      // 当前页容量
      pageSize: 10,
      // 当前页的数据
      tableData: [],
      // 总条数
      total: 0,
      drawer: false,
      direction: 'rtl',
      drawerType: '',
      form: {
        stem: '',
        content: ''
      },
      rules: {
        stem: [
          { required: true, message: '文章标题不可为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '文章内容不可为空', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getArticleList()
  },
  computed: {
    title () {
      let text = ''
      if (this.drawerType === 'add') {
        text = '添加面经'
      }
      if (this.drawerType === 'preview') {
        text = '面经预览'
      }
      if (this.drawerType === 'edit') {
        text = '编辑面经'
      }
      return text
    }
  },
  methods: {
    del (id) {
      // console.log(id)
      this.$confirm('您确定要删除该文章吗？', '温馨提示')
        .then(async () => {
          // 点击确定的时候执行
          // console.log('点击了确定')
          await delArticleApi(id)
          this.$message.success('删除成功')
          // 当前页是否只有1条
          // 当前页的页码是否 >1
          if (this.tableData.length === 1 && this.current > 1) {
            this.current--
          }
          this.getArticleList()
        })
        .catch(() => {
          // 点击取消的时候 执行
          // console.log('点击了取消')
        })
    },
    /**
     * 添加面经
     */
    confirmAdd () {
      this.$refs.form.validate(async (flag) => {
        if (!flag) return
        if (this.drawerType === 'add') {
          await createArticleApi(this.form)
          this.$message.success('恭喜！添加成功')
        }
        if (this.drawerType === 'edit') {
          const { id, content, stem } = this.form
          await editArticleApi({ id, content, stem })
          this.$message.success('恭喜！修改成功')
        }
        this.handleClose()
        this.current = 1
        this.getArticleList()
      })
    },
    /**
     * 关闭抽屉
     */
    handleClose () {
      this.drawer = false
      // resetFields 除了清空数据之外 还可以清空校验
      if (this.drawerType !== 'preview') {
        this.$refs.form.resetFields()
      }
      this.form = {
        stem: '',
        content: ''
      }
    },
    async openDrawer (type, id) {
      this.drawerType = type
      this.drawer = true
      if (type !== 'add') {
        const res = await getArticleDetailApi(id)
        this.form = { ...res.data }
      }
      // if (type === 'edit' || type === 'preview') {
      //   const res = await getArticleDetailApi(id)
      //   this.form = { ...res.data }
      // }
      // if (type === 'preivew') {
      //   const res = await getArticleDetailApi(id)
      //   this.form = { ...res.data }
      // }
    },
    handleCurrentChange (val) {
      this.current = val
      this.getArticleList()
    },
    async getArticleList () {
      const res = await getArticleListApi(this.current, this.pageSize)
      // console.log(res)
      this.tableData = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
